package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.execption.CommonError;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.content.service.CourseTeacherService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 课程预览、发布实现类
 * @Author dingchunlin
 * @Date 2024/4/4 16:17
 * @Version 1.0.0
 */
@Service
@Slf4j
public class CoursePublishServiceImpl implements CoursePublishService {

    @Autowired
    CourseBaseInfoService courseBaseInfoService;

    @Autowired
    TeachplanService teachplanService;

    @Autowired
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    CoursePublishMapper coursePublishMapper;

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseTeacherService courseTeacherService;

    @Autowired
    MqMessageService mqMessageService;

    @Autowired
    MediaServiceClient mediaServiceClient;


    /**
     * @param courseId 课程id
     * @return com.xuecheng.content.model.dto.CoursePreviewDto
     * @description 获取课程预览信息
     * @date 2022/9/16 15:36
     */
    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        //课程基本信息、营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);

        //课程计划信息
        List<TeachplanDto> teachplanTree= teachplanService.getTreeNodes(courseId);

        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplanTree);
        return coursePreviewDto;
    }

    /**
     * 提交审核
     *
     * @param companyId
     * @param courseId  课程id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commitAudit(Long companyId, Long courseId) {
        //如果课程的审核状态为已提交则不允许提交
        CourseBaseInfoDto courseBaseInfoDto = courseBaseInfoService.getCourseBaseInfo(courseId);
        if(courseBaseInfoDto == null){
            throw new XueChengPlusException("没有此课程!");
        }
        if (courseBaseInfoDto.getAuditStatus().equals("202003")){
            throw new XueChengPlusException("当前课程已提交审核请等待审核");
        }
        //课程的图片，信息是否完整，否则不让提交
        String pic = courseBaseInfoDto.getPic();
        if (StringUtils.isEmpty(pic)){
            throw new XueChengPlusException("请上传课程图片");
        }
        //本机构只允许提交本机构的课程
        if(!courseBaseInfoDto.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("不允许提交其它机构的课程。");
        }
        List<TeachplanDto> teachplanDtoList = teachplanService.getTreeNodes(courseId);
        if (teachplanDtoList.size() == 0 || teachplanDtoList == null){
            throw new XueChengPlusException("请编写课程计划");
        }
        //查询到课程基本信息，营销信息，课程计划等信息插入到课程预发布表
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfoDto,coursePublishPre);
        //1.1营销计划
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //转成json
        String jsonMarket = JSON.toJSONString(courseMarket);
        coursePublishPre.setMarket(jsonMarket);
        //1.2课程计划
        String jsonPlan = JSON.toJSONString(teachplanDtoList);
        coursePublishPre.setTeachplan(jsonPlan);
        //1.3教师信息
        List<CourseTeacher> teacherList = courseTeacherService.selectByCourseId(courseId);
        String jsonTeacher = JSON.toJSONString(teacherList);
        coursePublishPre.setTeachers(jsonTeacher);
        //1.4状态
        coursePublishPre.setStatus("202003");
        coursePublishPre.setCreateDate(LocalDateTime.now());
        //1.5设置机构id
        coursePublishPre.setCompanyId(companyId);
        //TODO 判断课程和当前机构是否是同一机构
        //查询预发布表是否存在数据
        CoursePublishPre coursePublishPreDb = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPreDb == null){
            //进行添加
            coursePublishPreMapper.insert(coursePublishPre);
        }else {
            //进行修改
            coursePublishPreMapper.updateById(coursePublishPre);
        }
        //更新课程基本信息表的审核状态为已提交
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //将状态修改为已提交
        courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);
    }

    /**
     * @param companyId 机构id
     * @param courseId  课程id
     * @return void
     * @description 课程发布接口
     */
    @Override
    @Transactional
    public void publish(Long companyId, Long courseId) {
        //查询预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPre == null) {
            XueChengPlusException.cast("课程没有审核记录,无法发布");
        }
        //只能发布本机构的课程
        if (!companyId.equals(coursePublishPre.getCompanyId())) {
            XueChengPlusException.cast("只能发布本机构的课程");
        }
        //查询课程的审核状态
        String status = coursePublishPre.getStatus();
        if (!status.equals("202004")) {
            XueChengPlusException.cast("课程未通过审核，不允许发布");
        }
        //向课程发布表写数据
        saveCoursePublish(courseId);
        //向消息表写数据
        saveCoursePublishMessage(courseId);
        //将预发布表数据删除
        coursePublishPreMapper.deleteById(courseId);

    }

    /**
     * 课程静态化
     *
     * @param courseId
     * @return
     */
    @Override
    public File generateCourseHtml(Long courseId) {
        //静态化文件
        File htmlFile  = null;

        try {
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());

            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");

            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");

            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);

            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            htmlFile = File.createTempFile("course",".html");
            log.debug("课程静态化，生成静态文件:{}",htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("课程静态化异常:{}",e.toString());
            XueChengPlusException.cast("课程静态化异常");
        }
        return htmlFile;
    }

    /**
     * 上传课程静态化页面
     *
     * @param courseId
     * @param file
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        String course = mediaServiceClient.uploadFile(multipartFile, "course/"+courseId+".html");
        if(course==null){
            XueChengPlusException.cast("上传静态文件异常");
        }

    }

    /**
     * 保存消息表记录
     * @param courseId
     */
    public void saveCoursePublishMessage(Long courseId){
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if (mqMessage == null){
            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
        }
    }

    /**
     * @description 保存课程发布信息
     * @param courseId  课程id
     */
    private void saveCoursePublish(Long courseId){
        // 获取课程预发布信息
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        // 若课程预发布信息为空，则抛出自定义异常
        if(coursePublishPre == null){
            XueChengPlusException.cast("课程预发布数据为空");
        }
        // 将课程预发布信息复制到课程发布信息对象中
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre,coursePublish);
        // 设置课程发布信息的状态为"203002"
        coursePublish.setStatus("203002");
        // 根据课程ID获取课程发布信息
        CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
        // 若课程发布信息为空，则插入新的课程发布信息，否则更新课程发布信息
        if(coursePublishUpdate == null){
            coursePublishMapper.insert(coursePublish);
        }else{
            coursePublishMapper.updateById(coursePublish);
        }
        // 根据课程ID获取课程基本信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        // 设置课程基本信息的状态为"203002"，并更新到数据库
        courseBase.setStatus("203002");
        courseBaseMapper.updateById(courseBase);
    }


}
